﻿using System;
using System.Collections.Generic;
using System.Data;
using Dapper;
using DapperLambdaSQL.BuildSQL;
using DapperLambdaSQL.Model;
using DapperLambdaSQL.Model.Exceptions;
using DapperLambdaSQL.Utils;

namespace DapperLambdaSQL
{
    public class DapperContext<T> where T : DbModel
    {
        /// <summary>
        /// Sql语句生成者
        /// </summary>
        internal readonly ISQLBuilder SqlBuilder;

        internal readonly SqlString SqlString;

        /// <summary>
        /// 数据库链接
        /// </summary>
        private readonly IDbConnection dbConnection;

        public DapperContext(ISQLBuilder sqlBuilder, IDbConnection dbConnection)
        {
            SqlString = new SqlString();
            SqlBuilder = sqlBuilder;
            this.dbConnection = dbConnection;
        }

        /// <summary>
        /// 返回列表
        /// </summary>
        /// <returns>数据集</returns>
        public List<T> ToList()
        {
            var sql = QuerySql();
            try
            {
                using (dbConnection)
                {
                    return dbConnection.Query<T>(sql).AsList();
                };
            }
            catch (Exception ex)
            {
                throw new ExecuteSqlException("ToList", ex);
            }
        }


        /// <summary>
        /// 核验查询语句
        /// </summary>
        /// <returns>SQL 语句</returns>
        private string QuerySql()
        {
            if (string.IsNullOrWhiteSpace(SqlString.Subject))
            {
                this.Select();
            }

            return SqlString.QuerySql;
        }
    }
}